package com.yl.ydk.presenter.impl

import android.content.Context
import androidx.fragment.app.Fragment
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.BaseFragmentPageAdapter
import com.yl.ydk.base.BasePresenter
import com.yl.ydk.bean.VideoCategoriesBean
import com.yl.ydk.presenter.contract.HealthyVideoHomeActivityContract
import com.yl.ydk.ui.fragment.HealthyVideoLisetFragment
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*

class HealthyVideoHomeActivityImpl : BasePresenter<HealthyVideoHomeActivityContract.View>(),
    HealthyVideoHomeActivityContract.Presenter<HealthyVideoHomeActivityContract.View> {


    private var mAdapter: BaseFragmentPageAdapter? = null
    private val mTitleList = ArrayList<String>()
    private val mFragments = ArrayList<Fragment>()

    override fun getVideoCategories(context: Context, vararg query: String?) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getVideoCategories()
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<VideoCategoriesBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: VideoCategoriesBean?) {
                        dismissLoadingDialog()
                        if (t?.data != null && t.code == 200) {
                            mFragments.clear()
                            mTitleList.clear()
                            mTitleList.add("全部")
                            mFragments.add(HealthyVideoLisetFragment.getInstance("全部",0))
                            t.data.forEach {
                                mTitleList.add(it.name)
                                mFragments.add(HealthyVideoLisetFragment.getInstance(it.name,it.id))
                            }
                            mAdapter = BaseFragmentPageAdapter(
                                mView?.getActivity()?.supportFragmentManager,
                                mFragments, mTitleList
                            )
                            mView?.getViewPager()?.adapter = mAdapter

                            mView?.getSlidingTabLayout()?.setViewPager(mView?.getViewPager())
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }


}